package com.team.app.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.stereotype.Repository;

import com.team.app.enums.ObjectType;
import com.team.app.model.Auth;
import com.team.app.model.AuthAcept;


@Repository
public class AuthAceptDaoImpl extends AbstractDao<AuthAcept> implements AuthAceptDao {
	AuthAceptDaoImpl(){
		super(AuthAcept.class);	
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<AuthAcept> findAll(Long urlId) {
		Session s=this.getCurrentSession();
		Query q = s.createQuery("from AuthAcept o where o.urlId = ?");
		q.setParameter(0, urlId);
		List<AuthAcept> result = q.list(); 		
		
		return result;		
	}

	@Override
	public AuthAcept find(Long urlId, Long objectId,Auth auth) {
		Session s=this.getCurrentSession();
		if(!auth.getObjectType().equals(ObjectType.TYPE_SERVICE)){			
			Query q = s.createQuery("from AuthAcept o where o.urlId = ? and o.objectId = ?");
			q.setParameter(0, urlId);
			q.setParameter(1, objectId);
			if(!q.list().isEmpty()){
				return (AuthAcept)q.list().get(0);
			}
		}else{
			Query q = s.createQuery("from AuthAcept o where o.urlId = ? and o.objectId = ? and o.companyId = ?");
			q.setParameter(0, urlId);
			q.setParameter(1, objectId);
			q.setParameter(2, auth.getCompanyId());
			if(!q.list().isEmpty()){
				return (AuthAcept)q.list().get(0);
			}
			
		}	
		
		return null;
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<AuthAcept> findByRole(Long roleId) {
		Session s=this.getCurrentSession();
		Query q = s.createQuery("from AuthAcept o where o.activeView = 1 and o.objectId = ? ");
		q.setParameter(0, roleId);
		List<AuthAcept> result = q.list(); 		
		
		return result;	
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<AuthAcept> findAll(Long urlId,Auth auth) {
		// TODO Auto-generated method stub
		Session s=this.getCurrentSession();
		List<AuthAcept> result = null;
		if(!auth.getObjectType().equals(ObjectType.TYPE_SERVICE.getKey())){			
			Query q = s.createQuery("from AuthAcept o where o.urlId = ? and o.companyId = ? ");
			q.setParameter(0, urlId);
			q.setParameter(1, auth.getCompanyId());
			result = q.list(); 		
		}else{
			
			Query q = s.createQuery("from AuthAcept o where o.urlId = ? and o.objectType = ?");
			q.setParameter(0, urlId);
			q.setParameter(1, auth.getObjectType());
			result = q.list(); 		
			
		}
		return result;	
	}

	@Override
	@SuppressWarnings("unchecked")
	public AuthAcept find(Long urlId, Long roleId) {
		// TODO Auto-generated method stub
		Session s=this.getCurrentSession();
		Query q = s.createQuery("from AuthAcept o where o.urlId = "+urlId+" and o.objectId = "+roleId);		
		List<AuthAcept> result = q.list(); 
		if(result.size() > 0){
			return result.get(0);
		}
		return null;
	}

}
